﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using JSTree.Sample.Models;

namespace JSTree.Sample.data
{
    public class NodesRepository
    {
        private NodesDbContext context;
        List<int> idsList = new List<int>(); 

        public NodesRepository()
        {
            context = new NodesDbContext(ConfigurationManager.ConnectionStrings["TreeConnectionString"].ConnectionString);
        }

        public IEnumerable<Node> GetNodes()
        {
           return context.Nodes; 
        }

        public void SetNameById(int id, string name)
        {
            var node = context.Nodes.FirstOrDefault(x => x.Id == id);
            if (node != null)
                node.Title = name;
            context.SaveChanges();
        }

        public void RemoveById(int id)
        {
            var rootNode = context.Nodes.FirstOrDefault(x => x.Id == id);
            if (rootNode == null) 
                { return; }
            DeleteSubNodes(rootNode);
            idsList.Add(rootNode.Id);
            foreach (int i in idsList)
            {
                context.Nodes.Remove(context.Nodes.FirstOrDefault(x => x.Id == i));
                context.SaveChanges(); 
            }
            idsList.Clear();
        }

        public void Move(Node node)
        {
            var tempNode = context.Nodes.FirstOrDefault(x => x.Id == node.Id);
            if (tempNode != null)
            {
                tempNode.ParentId = node.ParentId;
                context.SaveChanges();
            }
        }

        public void AddNode(Node node)
        {
            context.Nodes.Add(new Node(node.ParentId, node.Type, node.Title));
            context.SaveChanges();
        }

        public int GetIdBy(Node node)
        {
            var reqNode = context.Nodes.Where(x => x.ParentId == node.ParentId)
                .FirstOrDefault(y => y.Title == node.Title);
            if (reqNode != null)
                return reqNode.Id;
            return 0;
        }

        private void DeleteSubNodes(Node node)
        {
            var selNodes = context.Nodes.Where(x => x.ParentId == node.Id).ToList();
            if (!selNodes.Any())
            {
                return;
            }

            foreach (var selNode in selNodes)
            {
                Node childNode = new Node();
                childNode.Id = selNode.Id;
                idsList.Add(childNode.Id);
                DeleteSubNodes(childNode);
            }
        }

        public IEnumerable<Node> GetChildrenNodes(int id)
        {
            var nodes = context.Nodes.Where(x => x.ParentId == id);
            return nodes; 
        }
    }
}